﻿using System;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Events.Bus;
using Vecen.BangChuang.MultiTenancy;
using Abp.Runtime.Session;
using Abp.IdentityFramework;
using Vecen.BangChuang.Authorization.Users;
using Microsoft.AspNetCore.Identity;
using Vecen.BangChuang.BangChuang.DomainServices.Common;
using Vecen.BangChuang.Web;

namespace Vecen.BangChuang {
    /// <summary>
    /// Derive your application services from this class.
    /// </summary>
    public abstract class BangChuangAppServiceBase: ApplicationService {
        /// <summary>
        /// 客户端请求信息
        /// </summary>
        public IRequestInfo RequestInfo { get; set; } 
        /// <summary>
        /// 租户管理
        /// </summary>
        public TenantManager TenantManager { get; set; }

        /// <summary>
        /// 用户管理
        /// </summary>
        public UserManager UserManager { get; set; }

        /// <summary>
        /// 事件总线
        /// </summary>

        public IEventBus EventBus { get; set; }


        /// <summary>
        /// 附件管理
        /// </summary>
        public AttachmentManager AttachmentManager { get; set; }

        /// <summary>
        /// 
        /// </summary>
        protected BangChuangAppServiceBase() {
            LocalizationSourceName = BangChuangConsts.LocalizationSourceName;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected virtual Task<User> GetCurrentUserAsync() {
            var user = UserManager.FindByIdAsync(AbpSession.GetUserId().ToString());
            if(user == null) {
                throw new Exception("There is no current user!");
            }

            return user;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected virtual Task<Tenant> GetCurrentTenantAsync() {
            return TenantManager.GetByIdAsync(AbpSession.GetTenantId());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="identityResult"></param>
        protected virtual void CheckErrors(IdentityResult identityResult) {
            identityResult.CheckErrors(LocalizationManager);
        }
    }
}